﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Drawing;
using BytesRoad.Net.Ftp;
using System.Web;
using System.Diagnostics;
using System.ComponentModel;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Net;

namespace ADayRoiAdmin
{
    class AdayroiClass
    {

        private FtpClient ftp_client = new FtpClient();
        private byte[] downloadedData;
        string temp_folder=Directory.GetCurrentDirectory();
        Dictionary<int, byte[]> _myAttachments;
        public AdayroiClass(ref SqlConnection con)
        {
            con = check_login("buyall_user", "b@y@ll", false);
            //con = check_login("sa", "123", false);
            _myAttachments = new Dictionary<int, byte[]>();
        }

        public SqlConnection check_login(string username, string password, bool remember)
        {
            //string sketnoi = @"Data Source=dumen-pc\localhost;Initial Catalog=BANHANG;Integrated Security=True";

            string sketnoi = @"Database=buyall_db;Server=112.78.2.170,1455;";
            ////string sketnoi = @"Database=ADayRoi;Server=.\Localhost;";
            SqlConnection con = null;
            if (username == "" && password == "")
                sketnoi += @"Integrated Security = true";
            else
               sketnoi += @"uid=" + username + @";pwd=" + password;

            con = new SqlConnection(sketnoi);
           
            return con;

        }

        public string get_path_pic()
        {
            OpenFileDialog picture_dialog = new OpenFileDialog();
            picture_dialog.Title = "Choose Image";

            picture_dialog.FileName = "";
            picture_dialog.ShowDialog();

            return picture_dialog.FileName;
        }

        public int UpdateSQL(SqlConnection con, string sql)
        {
            int maloi = 0;
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sql;
            try
            {
                if (con.State == ConnectionState.Closed)
                    con.Open();
                cmd.ExecuteNonQuery();

                con.Close();
            }
            catch (SqlException ex)
            {
                maloi = -1;
                if (ex.ToString().Contains("UNIQUE KEY"))
                {
                    if (ex.ToString().Contains("ProductCode"))
                        MessageBox.Show("Ma sp bi trung");
                    else
                        MessageBox.Show("ma bi trung");
                }
                else
                    MessageBox.Show("Lỗi " + ex.ToString());
            }
            return maloi;
        }

        public int UpdateSQL(SqlConnection con, ref SqlTransaction trans, string sql)
        {
            int maloi = 0;
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sql;
            try
            {
                cmd.Transaction = trans;
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                maloi = -1;
                if (ex.ToString().Contains("UNIQUE KEY"))
                {
                    if (ex.ToString().Contains("ProductCode"))
                        MessageBox.Show("Ma sp bi trung");
                    else
                        MessageBox.Show("ma bi trung");
                }
                else
                    MessageBox.Show("Lỗi " + ex.ToString());
            }
            return maloi;
        }

        public int GETPKID(SqlConnection con, string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sql;
            int pkid = 0;
            try
            {
                if (con.State == ConnectionState.Closed)
                    con.Open();
                pkid = Convert.ToInt32(cmd.ExecuteScalar());
                con.Close();
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Lỗi " + ex.ToString());
            }
            return pkid;
        }

        public DataTable getList(string sql,SqlConnection con)
        {

            SqlCommand cmd = new SqlCommand(sql, con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            try
            {
                if (con.State == ConnectionState.Closed)
                    con.Open();
                adapter.Fill(ds);
                dt = ds.Tables[0];
                con.Close();

            }
            catch (SqlException ex)
            {
                //MessageBox.Show("Lỗi: " + ex.ToString());
            }
            return dt;
        }

        #region ftp


        public string loadpicture(string picture_file, PictureBox pic)
        {

            if (picture_file != String.Empty && pic != null)
            {
                try
                {
                    FileInfo fileinfo = new FileInfo(picture_file);
                    if (!fileinfo.Exists) return null;
                    else
                    {
                        byte[] fileBytes;
                        using (FileStream fs = fileinfo.OpenRead())
                        {
                            fileBytes = new byte[fs.Length];
                            fs.Read(fileBytes, 0, fileBytes.Length);
                            fs.Dispose();
                        }

                        MemoryStream ms = new MemoryStream(fileBytes);
                        Image temp = Image.FromStream(ms);

                        pic.Image = temp;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("File broken. Please choose again\n" + ex.ToString());
                }
            }

            return picture_file;
        }

        public void downloadFile(string FTPAddress, string filepath, string ftpfile, string username, string password)
        {
            downloadedData = new byte[0];

            try
            {
                //Optional
                Application.DoEvents();

                //Create FTP request
                //Note: format is ftp://server.com/file.ext
                FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + ftpfile) as FtpWebRequest;

                //Optional
                Application.DoEvents();

                //Get the file size first (for progress bar)
                request.Method = WebRequestMethods.Ftp.GetFileSize;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = true; //don't close the connection

                int dataLength = (int)request.GetResponse().ContentLength;

                //Optional
                Application.DoEvents();

                //Now get the actual data
                request = FtpWebRequest.Create(FTPAddress + "/" + ftpfile) as FtpWebRequest;
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false; //close the connection when done

                //Set up progress bar

                //Streams
                FtpWebResponse response = request.GetResponse() as FtpWebResponse;
                Stream reader = response.GetResponseStream();

                //Download to memory
                //Note: adjust the streams here to download directly to the hard drive
                MemoryStream memStream = new MemoryStream();
                byte[] buffer = new byte[1024]; //downloads in chuncks

                while (true)
                {
                    Application.DoEvents(); //prevent application from crashing

                    //Try to read the data
                    int bytesRead = reader.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        Application.DoEvents();
                        break;
                    }
                    else
                    {
                        //Write the downloaded data
                        memStream.Write(buffer, 0, bytesRead);
                        //Update the progress bar

                    }
                }

                //Convert the downloaded stream to a byte array
                downloadedData = memStream.ToArray();

                //Clean up
                reader.Close();
                memStream.Close();
                response.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Lỗi trong quá trình load file. Vui lòng liên hệ IT.");
                return;
            }
            try
            {
                FileStream newFile = new FileStream(filepath, FileMode.Create);
                newFile.Write(downloadedData, 0, downloadedData.Length);
                newFile.Close();

                username = string.Empty;
                password = string.Empty;
            }
            catch
            {
                MessageBox.Show("vui lòng đóng file trước khi tiếp tục");
                return;
            }
        }

        public string lay_hinh(string picture_file, PictureBox pic)
        {
            string filepath = temp_folder + picture_file.Replace('/', '\\');
            downloadFile("ftp://buyall.vn/httpdocs", filepath, picture_file, "buyall", "P@sSw0rd&%#23w");

            if (filepath != String.Empty && pic != null)
            {
                try
                {
                    FileInfo fileinfo = new FileInfo(filepath);
                    if (!fileinfo.Exists) return null;
                    else
                    {
                        byte[] fileBytes;
                        using (FileStream fs = fileinfo.OpenRead())
                        {
                            fileBytes = new byte[fs.Length];
                            fs.Read(fileBytes, 0, fileBytes.Length);
                            fs.Dispose();
                        }

                        MemoryStream ms = new MemoryStream(fileBytes);
                        Image temp = Image.FromStream(ms);

                        pic.Image = temp;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("File bị gián đoạn. VUi lòng chọn lại file\n" + ex.ToString());
                }
            }

            return filepath;
        }

        public int ftp_picture(string picture_load, string picture_ftp)
        {
            int error_ftp = 0;
            if (!String.IsNullOrEmpty(picture_load))
            {
                try
                {
                    uploadFile("ftp://buyall.vn/httpdocs", picture_load, picture_ftp, "buyall", "P@sSw0rd&%#23w");
                }
                catch (FtpTimeoutException ex)
                {
                    MessageBox.Show(ex.ToString());
                    error_ftp = -1;
                }
            }
            return error_ftp;
        }

        private void uploadFile(string FTPAddress, string filePath, string ftpfile, string username, string password)
        {
            //Create FTP request
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress + "/" + ftpfile);

            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(username, password);
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = false;

            //Load the file
            FileStream stream = File.OpenRead(filePath);
            byte[] buffer = new byte[stream.Length];

            stream.Read(buffer, 0, buffer.Length);
            stream.Close();

            //Upload file
            Stream reqStream = request.GetRequestStream();
            reqStream.Write(buffer, 0, buffer.Length);
            reqStream.Close();
        }

        public int deleteFile(string FTPAddress,string ftpFolder, string fileName)
        {
            int error_delete = 0;

            try
            {
                FtpWebRequest requestFileDelete = (FtpWebRequest)WebRequest.Create(FTPAddress + ftpFolder + fileName);
                requestFileDelete.Credentials = new NetworkCredential("buyall", "P@sSw0rd&%#23w");
                requestFileDelete.Method = WebRequestMethods.Ftp.DeleteFile;

                FtpWebResponse responseFileDelete = (FtpWebResponse)requestFileDelete.GetResponse();
            }
            catch { error_delete = -1; }

            return error_delete;
        }

        public string convert_to_ftp_file(string fullname,  string file_extension, string temp_file)
        {
            string fullname_ftp_file = fullname.Replace(" ", "_");
            try
            {
                file_extension = Convert.ToDateTime(file_extension).ToShortDateString().Replace("/", "");
            }
            catch { }
            string extension = Path.GetExtension(temp_file);

            if (file_extension != String.Empty)
                fullname_ftp_file += "_" + file_extension;

            fullname_ftp_file += extension;

            return fullname_ftp_file;
        }
        #endregion

        public void key_press(object sender, KeyPressEventArgs e)
        {
            int isNumber = 0;
            e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);
            if (Convert.ToInt32(e.KeyChar) == 8)
                e.Handled = false;
        }
    }
}

